package com.jy.project.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jy.project.domain.User;
import com.jy.project.ex.BizException;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class JwtUtils {

    public static final String SECRET = "com.jy.secret";

    public static final String ISSUER = "user";

    /**
     * 生成token
     *
     * @param
     * @return
     */
    public static String sign(User user) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTCreator.Builder builder = JWT.create()
                    .withIssuer(ISSUER);
            builder.withClaim("id", user.getId());
            builder.withClaim(" deptNo", user.getDeptNo());
            builder.withClaim("date", new Date());
            return builder.sign(algorithm);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("创建token失败");
        }
    }

    /**
     * 验证jwt，并返回数据
     */
    public static User verifyToken(String token) {

        Algorithm algorithm=null;
        Map<String, Claim> map = null;
        try {
            algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            DecodedJWT jwt = verifier.verify(token);
            map = jwt.getClaims();
        } catch (Exception e) {
            throw new BizException("token不正确");
        }
        Iterator<Map.Entry<String, Claim>> iterator = map.entrySet().iterator();
        User user = new User();
        while (iterator.hasNext()) {
            Map.Entry<String, Claim> entry = iterator.next();
            if (entry.getKey().equals("id")){
                user.setId(entry.getValue().asLong());
            }
            if (entry.getKey().equals("deptNo")){
                user.setDeptNo(entry.getValue().asString());
            }
        }
        return user;
    }
}
